package com.example.qxfw.backgroundManagement.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.qxfw.backgroundManagement.mapper.UserManagementFirstMapper;
import com.example.qxfw.backgroundManagement.service.UserManagerFirstService;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.UserTable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/************************************
 *
 * @author : HuangDeYin Jolly
 * @since : JDK 11
 * @Date : 2023/7/4  星期二   9:48
 * @description : 此类用来 用户管理1 的控制层
 ***************************************/
@ApiIgnore
@Api(tags = "后台管理-用户管理1")
@RestController
@CrossOrigin
@RequestMapping("/UserManagementFirst")
public class UserManagementFirstController {

    @Autowired
    private UserManagerFirstService userManagerFirstService;

    @Autowired
    private UserManagementFirstMapper userManagementFirstMapper;

    @ApiOperation("根据页数查询")
    @RequestMapping(value = "selectUserTable")
    public SysResult selectUserTable(int pageNum) {
        List<UserTable> userTables = this.userManagerFirstService.selectUserTable(pageNum);
        return SysResult.success(userTables);
    }

    @ApiOperation("查询用户人数")
    @RequestMapping(value = "selectCountUserTable")
    public SysResult selectCountUserTable() {
        Integer selectCountUserTable = this.userManagerFirstService.selectCountUserTable();
        return SysResult.success(selectCountUserTable);
    }

    @ApiOperation("条件查询")
    @RequestMapping(value = "queryUserTable")
    public SysResult queryUserTable(String startTime, String endTime, String userName) {
        List<UserTable> userTables = this.userManagerFirstService.queryUserTable(startTime, endTime, userName);
        return SysResult.success(userTables);
    }

    @ApiOperation("插入用户数据")
    @RequestMapping(value = "insertUserTable")
    public SysResult insertUserTable(UserTable userTable) {
        List<UserTable> userTables = this.userManagerFirstService.selectByUserName(userTable.getUsername());
        if (userTables != null && userTables.size() > 0) {
            return SysResult.fail("此用户已存在");
        } else {
            Integer saveUserTable = this.userManagerFirstService.saveUserTable(userTable);
            return returnInformation("插入用户信息", saveUserTable);
        }
    }

    @ApiOperation("更新用户信息")
    @RequestMapping(value = "updateUserTable")
    public SysResult updateUserTable(String userName, String password, String serviceWebAddress, String serviceWechatAddress, String inputTime, String performer) {
        List<UserTable> userTables = this.userManagerFirstService.selectByUserName(userName);
        if (userTables != null && userTables.size() > 0) {
            Integer updateUserTable = this.userManagerFirstService.updateUserTable(userName, password, serviceWebAddress, serviceWechatAddress, inputTime, performer);
            return returnInformation("更新用户信息", updateUserTable);
        } else {
            return SysResult.fail("没有此用户信息");
        }

    }

    @ApiOperation("删除用户信息")
    @RequestMapping(value = "deleteUserTable")
    public SysResult deleteUserTable(String userName) {
        Integer deleteUserTable = this.userManagerFirstService.deleteUserTable(userName);
        return returnInformation("删除用户信息", deleteUserTable);
    }

    @RequestMapping(value = "exportUserTable")
    public void exportUserTable(HttpServletResponse response) throws UnsupportedEncodingException {
        List<UserTable> userTables = this.userManagerFirstService.exportUserTable();
        ExcelWriter writer = ExcelUtil.getWriter();
        /*定义标题*/
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("servicewebaddress", "服务网站地址");
        writer.addHeaderAlias("servicewechataddress", "服务微信地址");
        writer.addHeaderAlias("inputtime", "录入时间");
        writer.addHeaderAlias("performer", "办理人");

        writer.setOnlyAlias(true);

        writer.write(userTables, true);
        /*设置响应的内容类型为二进制流*/
        response.setContentType("application/octet-stream");
        String format = "xlsx";
        String fileName = "userTable";
        /*通过调用setHeader方法设置名为"Content-Disposition"的响应头部信息
         * attachment表示以附件形式下载，
         * filename后面跟着要下载的文件名*/
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + "." + format);
        /*response.getOutputStream()获取到响应的输出流
         * true表示在数据写入完成后自动刷新输出流*/
        try (ServletOutputStream out = response.getOutputStream()) {
            // 将内容写入输出流并刷新
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            writer.close();
        }
    }

    @RequestMapping(value = "download")
    public void studentDownload(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename=userTable.xlsx");
        File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "userTable.xlsx");
        FileInputStream inputStream = new FileInputStream(file);
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", "" + file.length());
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.flush();
        outputStream.close();
    }

    @ApiOperation("导入数据")
    @RequestMapping(value = "importUserTable")
    public SysResult importUserTable(MultipartFile importFile) throws IOException {
        if (importFile.isEmpty()) {
            return SysResult.fail("请选择要上传的文件");
        }
        Integer idMax = this.userManagementFirstMapper.selectIdMax();
        ExcelReader excelReader = ExcelUtil.getReader(importFile.getInputStream());
        List<List<Object>> list = excelReader.read(1);
        final AtomicInteger a = new AtomicInteger();
        list.forEach(userTableList -> {
            String pattern = "yyyy-MM-dd";
            DateFormat dateFormat = new SimpleDateFormat(pattern);
            UserTable userTable = new UserTable();
            userTable.setUsername(String.valueOf(userTableList.get(0)));
            userTable.setPassword(String.valueOf(userTableList.get(1)));
            userTable.setServicewebaddress(String.valueOf(userTableList.get(2)));
            userTable.setServicewechataddress(String.valueOf(userTableList.get(3)));
            userTable.setPerformer(String.valueOf(userTableList.get(5)));
            Object o = userTableList.get(4);
            if (o != null) {
                try {
                    userTable.setInputtime(dateFormat.parse(String.valueOf(o)));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            userTable.setId(idMax);
            SysResult sysResult = this.insertUserTable(userTable);
            a.set(1);
        });
        return returnInformation("数据导入", 1);
    }


    public SysResult returnInformation(String info, Integer result) {
        if (result < 0) {
            return SysResult.fail(info + "失败");
        } else {
            return SysResult.success(info + "成功");
        }
    }
}
